//
//  InputView.m
//  OperationPro
//
//  Created by yaxue wang on 2017/1/3.
//  Copyright © 2017年 展鸿科技. All rights reserved.
//

#import "InputView.h"
#import "InputModel.h"
#import "CInputBoxView.h"
#import "CompleteView.h"
#import "LoadingView.h"
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "InputTopCell.h"
#import "InputCenterCell.h"
#import "CModelAction.h"
#import "DataModel.h"
#import <AVFoundation/AVFoundation.h>
#import <AFNetworking/AFNetworking.h>
#import "InputCell.h"

@interface InputView()

@property (nonatomic, strong)AVAudioPlayer *audioPlayer;

@property (nonatomic,strong)UIView *noDataView;
@end
@implementation InputView
- (void)initView{
    [super initView];
   
    [self setShowNoDataNotice:@"没有内容"];
    self.backgroundColor =[UIColor clearColor];
    self.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.showsVerticalScrollIndicator =NO;
    [self registerCell:[InputTopCell class] withModel:[InputModel class]];
    [self registerCell:[InputCenterCell class] withModel:[InputModel class]];
     [self setDataWithUrl:@"home_pagedOrdersCreatedByMe" andParam:nil];
    [self setTableActionType:CTableActionType_Both];
    [self loadData];
}

- (void)initData
{
    [super initData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.mainData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 65;
    }else {
        InputModel *order = [self.mainData objectAtIndex:indexPath.section];
        CGFloat equitmetHeight;
        CGFloat textDescridHeight;
        NSString *equitString;
        NSString *textDescride;
        
        if ((order.H_machine_name ==nil||[order.H_machine_name isEqualToString:@""])&&(order.H_machine_type_name ==nil||[order.H_machine_type_name isEqualToString:@""])) {
            equitString=@"";
            equitmetHeight=0;
        }else if ((order.H_machine_name ==nil||[order.H_machine_name isEqualToString:@""])||(order.H_machine_type_name ==nil||[order.H_machine_type_name isEqualToString:@""])) {
            
            if(order.H_machine_name ==nil||[order.H_machine_name isEqualToString:@""]){
                equitmetHeight=25;
                equitString=order.H_machine_type_name;
            }else if(order.H_machine_type_name ==nil||[order.H_machine_type_name isEqualToString:@""]){
                equitmetHeight=25;
                equitString=order.H_machine_name;
                
            }
        }else
        {
            equitString =[NSString stringWithFormat:@"%@%@",order.H_machine_type_name,order.H_machine_name];
            CGSize equitmetSize  = [equitString sizeWithFont:F(12) constrainedToSize:CGSizeMake(WindowWidth-95, 900)];
            equitmetHeight=10+equitmetSize.height;
        }
        
        
        if ((order.H_textdescribe ==nil||[order.H_textdescribe isEqualToString:@""])) {
            textDescride=@"";
            textDescridHeight=0;
        }else
        {
            textDescride=order.H_textdescribe;
            
            CGSize textDescridSize = [textDescride sizeWithFont:F(12) constrainedToSize:CGSizeMake(WindowWidth-95, 900)];
            textDescridHeight=textDescridSize.height+10+10;
            
            
        }
        NSString*imgStr=order.H_image;
        NSString *videoStr=order.H_video;
        CGFloat imgHeight;
        CGFloat width =(WindowWidth-95-30)/3;
        if (imgStr ==nil||[imgStr isEqualToString:@""]){
            if(videoStr.length>0){
                imgHeight=width+10;
                
            }else
            {
                imgHeight=0;
            }
        }else
        {
            NSArray *array= [imgStr componentsSeparatedByString:@","];
            
            if (array.count>2&&videoStr.length>0) {
                imgHeight=(width+10)*2+10;
            }else
            {
                imgHeight=width+10;
                
            }
        }
        CGFloat audioHeight;
        if ((order.H_audio ==nil||[order.H_audio isEqualToString:@""])) {
            audioHeight=0;
        }else
        {
            CGFloat videocompressHeight;
            if ((order.H_audio_translator ==nil||[order.H_audio_translator isEqualToString:@""])) {
                videocompressHeight=0;
            }else
            {
                NSString *string=[NSString stringWithFormat:@"(%@)",order.H_audio_translator];
                
                CGSize  videocompressSize  = [string sizeWithFont:F(12) constrainedToSize:CGSizeMake(WindowWidth-95, 900)];
                videocompressHeight=5+videocompressSize.height;
            }
            
            audioHeight=30+10+videocompressHeight;
        }
        return MAX((equitmetHeight)+(textDescridHeight)+5+imgHeight+(audioHeight), 15);
    }
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view =[[UIView alloc]init];
    view.backgroundColor =[UIColor clearColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0;
        
    }else
    {
        return 5;
        
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *classarray = @[[InputTopCell class],[InputCenterCell class]];
    Class class = classarray[indexPath.row];
    if (class == nil) {
        class = [InputCell class];
    }
    NSString *cellID = [NSString stringWithFormat:@"Cell_%@", NSStringFromClass(class)];
    InputCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[class alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    if (self.mainData.count == 0) {
        [cell setModel:nil];
        return cell;
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    [cell setModel:self.mainData[indexPath.section]];
 
    [cell setBtnBlock:^(InputCell *c, InputCellType type, NSString *imgNUm) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"stopPlayer" object:nil];
        
        NSIndexPath *path = [tableView indexPathForCell:c];
        InputModel *data = self.mainData[path.section];
        NSInteger num=[data.H_state integerValue];
        
        if (type==InputCellType_Img) //图片
        {
            if (self.blowUpImg) {
                if (self.mainData.count == 0) {
                    self.blowUpImg(nil,nil);
                    return;
                }
                self.blowUpImg(data,imgNUm);
            }
            
        }else if (type==InputCellType_Sound)//声音
        {
            NSString*urlString =[CClass getCacheData:qnDomain];
            for (int i = 0; i < self.mainData.count; i ++) {
                NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:i];
                InputCenterCell *cell = [self cellForRowAtIndexPath:path];
                [cell stopPlayer];
            }
            [self.audioPlayer stop];
            self.audioPlayer = nil;
            //1.音频文件的url路径
            NSURL *voiceUrl =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,data.H_audio]];
            //远程地址
            NSURL *URL = voiceUrl;
            //默认配置
            NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
            
            //AFN3.0+基于封住URLSession的句柄
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
            
            //请求
            NSURLRequest *request = [NSURLRequest requestWithURL:URL];
            
            //下载Task操作
            NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                
                //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
                
                NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
                return [NSURL fileURLWithPath:path];
                
            } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                //设置下载完成操作
                // filePath就是你下载文件的位置，你可以解压，也可以直接拿来使用
                NSData * audioData = [NSData dataWithContentsOfURL:filePath];
                //播放录音
                AVAudioSession *seesion= [AVAudioSession sharedInstance];
                //混音播放
                
                [seesion setCategory:AVAudioSessionCategoryPlayback error:nil];
                [seesion setActive:YES error:nil];
                
                self.audioPlayer=[[AVAudioPlayer alloc]initWithData:audioData error:nil];
                if (self.audioPlayer  == nil)
                {
                    echo(([NSString stringWithFormat:@"ERror creating player: %@", [error description]]));
                }else{
                    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopPlayer:) name:@"stopPlayer"object:nil];
                    [c startAnimate:[NSString stringWithFormat:@"%ld s",(long)self.audioPlayer .duration]];
                    
                    //准备播放
                    [self.audioPlayer  prepareToPlay];
                    //播放
                    [self.audioPlayer  play];
                    //            //开始动画
                    //                    [cell.soundImg startAnimating];
                    __block  NSInteger duration = (NSInteger)self.audioPlayer.duration;
                    NSTimeInterval period = 1.0; //设置时间间隔
                    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
                    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
                    dispatch_source_set_event_handler(_timer, ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                        });
                        if (duration -- <= 0 ) {
                            dispatch_source_cancel(_timer);
                            dispatch_async(dispatch_get_main_queue(), ^{
                                
                                //关闭动画
                                [c stopPlayer];
                                
                            });
                        }
                    });
                    dispatch_resume(_timer);
                    
                }
            }];
            [downloadTask resume];
            
        }else if (type==InputCellType_Detail)//详情
        {
            if (self.goToNextDetail) {
                if (self.mainData.count == 0) {
                    self.goToNextDetail(nil);
                    return;
                }
                self.goToNextDetail(data);
            }
        }
        
        
    }];
    
    
    
    return cell;
}
- (void)stopPlayer:(NSNotification*)noti
{
    for (int i = 0; i < self.mainData.count; i ++) {
        NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:i];
        InputCenterCell *cell = [self cellForRowAtIndexPath:path];
        [cell stopPlayer];
    }
    [self.audioPlayer stop];
    self.audioPlayer = nil;
    
}

@end
